package com.steak.orm.builder;

import com.steak.orm.tool.StringUtil;

import java.lang.reflect.Field;

/**
 * @author 刘牌
 * @Title:
 * @date 2022/3/414:08
 */
public class SaveSQLBuilder extends BaseSQLBuilder {
    public String saveSQL(Object obj) throws Exception {
        getTableName(obj);
        sqlBuilder.append(INSERT + INTO).append(tableName).append("(");
        //VALUES拼装
        StringBuilder valuesBuilder = new StringBuilder();
        valuesBuilder.append(VALUES).append("(");
        Field[] fields = getFields(obj);
        for (int i = 0; i < fields.length; i++) {
            String fieldName = StringUtil.getLastStr(fields[i].toString());
            Object value = obj.getClass().getMethod(getField(fieldName)).invoke(obj);
            //新增要去掉主键
            if (hasPrimaryKey(fields[i]) && (null == value || "".equals(value))){
               continue;
            }
            if (i + 1 == fields.length){
                sqlBuilder.append(fieldName).append(")");
                valuesBuilder.append("'").append(value).append("'").append(")");
            }else {
                sqlBuilder.append(fieldName).append(",");
                valuesBuilder.append("'").append(value).append("'").append(",");
            }
        }
        return (sqlBuilder.toString() + valuesBuilder);
    }
}
